import { InjectionToken, Lifecycle, scoped, singleton } from "tsyringe";
import { IConfig } from "../core/config";
import { getTokenDefault } from "../utils/getTokenDefault";
import { parseJson } from "../utils/parseJson";
import { Storage } from 'storages'
@scoped(Lifecycle.ContainerScoped)
export class Config implements IConfig {
    storage: Storage;
    constructor() {
        this.storage = storages.create(`com.sker.auto`)
    }
    remove<T>(key: InjectionToken<T>): void {
        this.storage.remove(key as string)
    }
    has<T>(key: InjectionToken<T>): boolean {
        return this.storage.contains(key as string)
    }
    clear(): void {
        this.storage.clear()
    }
    get<T>(key: InjectionToken<T>): T {
        let item = this.storage.get(key as string)
        let val = parseJson(item)
        if (!val || val === 'undefined') {
            val = getTokenDefault(key)
            this.set(key, val)
        }
        return val;
    }
    set<T>(key: InjectionToken<T>, val: T): void {
        if (typeof val === 'object') {
            this.storage.put(key as string, JSON.stringify(val))
        } else {
            this.storage.put(key as string, `${val}`)
        }
    }
    getSafe<T>(key: InjectionToken<T>, def: T): T {
        return this.storage.get(key as string, def)
    }
}